<template>
	<view class="submit-form" :style="{ direction: $store.state.dir }">
		<view class="page-title h2">
			{{ $t('edit-house.title') }}
		</view>
		<icon-label :text="$t('property.title')" icon="icon-description"></icon-label>
		<input class="form-input" v-model="title" maxlength="128" />
		<!-- $t('property.location') -->
		<icon-label :text="$t('select.region')" icon="icon-location"></icon-label>
		<view class="form-input" @click="handleShow">
			<p class="line1" style="float: left;max-width: 90%;">{{area_name||'Please choose'}}</p>
			<u-icon name="arrow-right" style="float: right;margin-top:10px;"></u-icon>
		</view>
		<!-- <uni-data-select :clear="false" v-model="city" :localdata="cityItems" placeholder="Select"></uni-data-select> -->
		<!-- <icon-label :text="$t('property.mapLocation')" icon="icon-location"></icon-label>
		<view class="form-input" @click.stop="goWebView">
			<p class="line1" style="float: left;max-width: 90%;">{{mapname}}</p>
			<u-icon name="arrow-right" style="float: right;margin-top:10px;"></u-icon>
		</view> -->
		<icon-label :text="$t('property.address')" icon="icon-description"></icon-label>
		<input class="form-input" v-model="address" />
		<icon-label :text="$t('property.label')" icon="icon-description"></icon-label>
		<input class="form-input" v-model="labels" />
		<view class="info_radio">
			<ul>
				<li :class="furnished==index?'active row':'row'" v-for="(item, index) in radioList" :key="index"
					@click.stop="handleRadio(index)">
					<image v-if="furnished == index" src="/static/choose-active.png" mode=""> </image>
					<image v-else src="/static/choose-gray.png" mode=""></image>
					<p>{{ item.name }}</p>
				</li>
			</ul>
		</view>
		<view v-if="furnished==0">
			<icon-label :text="$t('property.price')" icon="icon-pay"></icon-label>
			<view class="flex-layout-row" style="margin-top: 28rpx;">
				<input class="form-input" v-model="rentPrice" style="width: 80%;"
					:placeholder="$t('property.price')" />
				<span style="padding-left: 30rpx;line-height:80rpx;">{{ $t('text.egp.month') }}</span>
			</view>
		</view>
		<view v-if="furnished==1">
			<icon-label :text="$t('title.day')" icon="icon-pay"></icon-label>
			<view class="flex-layout-row" style="margin-top: 28rpx;">
				<input class="form-input" v-model="familyPrice" style="width: 80%;"
					:placeholder="$t('property.price')" />
				<span style="padding-left: 30rpx;line-height:80rpx;">{{ $t('text.egp.day') }}</span>
			</view>
			<icon-label :text="$t('title.week')+'(7-15days)'" icon="icon-pay"></icon-label>
			<view class="flex-layout-row" style="margin-top: 28rpx;justify-content: space-between;">
				<view class="row">
					
					<input class="form-input" type="number" maxlength="3" v-model="weekDiscount" style="width: 60%;margin-right: 10rpx;"
						:placeholder="$t('property.discount')" />%<span
						style="margin-left: 24rpx;" v-if="weekPrice>0">{{weekPrice}}</span>
				</view>
		
				<span style="padding-left: 30rpx;line-height:80rpx;">{{ $t('text.egp.day') }}</span>
			</view>
			<icon-label :text="$t('title.Month')+'(16-30days)'" icon="icon-pay"></icon-label>
			<view class="flex-layout-row" style="margin-top: 28rpx;justify-content: space-between;">
				<view class="row">
					<input class="form-input" type="number" maxlength="3"    v-model="monthDiscount" style="width: 60%;margin-right: 10rpx;"
						:placeholder="$t('property.discount')" />%<span
						style="margin-left: 24rpx;" v-if="monthPrice>0">{{monthPrice}}</span>
				</view>
		
				<span style="padding-left: 30rpx;line-height:80rpx;">{{ $t('text.egp.day') }}</span>
			</view>
			<icon-label :text="$t('text.Longterm')" icon="icon-pay"></icon-label>
			<view class="flex-layout-row" style="margin-top: 28rpx;">
				<input class="form-input" v-model="rentPrice" style="width: 80%;"
					:placeholder="$t('property.price')" />
				<span style="padding-left: 30rpx;line-height:80rpx;">{{ $t('text.egp.month') }}</span>
			</view>
		</view>
		<icon-label :text="$t('property.cleanfee')" icon="icon-pay"></icon-label>
		<view class="flex-layout-row" style="margin-top: 28rpx;">
			<input class="form-input" v-model="cleanfee" style="width: 80%;"
				:placeholder="$t('property.cleanfee')" />
				<span style="padding-left: 30rpx;line-height:80rpx;">EGP</span>
			<!-- <uni-data-select :clear="false" class="gap-row" style="width: 40%;" v-model="unit"
				:localdata="unitItems" placeholder="Select"></uni-data-select> -->
		</view>
		<!-- <uni-data-select :clear="false" v-model="type" :localdata="typeItems" placeholder="Select"></uni-data-select> -->
		<icon-label :text="$t('property.houseType')" icon="icon-property-type"></icon-label>
		<uni-data-select :clear="false" v-model="houseType" :localdata="houseItems"
			placeholder="Select"></uni-data-select>
		<icon-label :text="$t('property.bedrooms')" icon="icon-bedroom"></icon-label>
		<input type="number" class="form-input" v-model="bedrooms" />
		<icon-label :text="$t('property.bathrooms')" icon="icon-bathroom"></icon-label>
		<input type="number" class="form-input" v-model="bathrooms" />
		<icon-label :text="$t('property.area')" icon="icon-area"></icon-label>
		<input type="decimal" class="form-input" v-model="area" />
		<view class="row">
			<icon-label :text="$t('property.images')" icon="icon-bedroom"></icon-label><text class="copy"
				@click.stop="handleCopy">{{$t('property.url.title')}}</text>
		</view>
		<u-upload :fileList="images" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="30"></u-upload>
		<icon-label :text="$t('property.description')" icon="icon-description"></icon-label>
		<textarea v-model="description" confirm-hold :maxlength="1000"></textarea>
		<u-button class="gap-col-top2" type="primary" shape="circle" @click="handleSubmit">
			{{ $t('edit-house.submitButton') }}
		</u-button>
		<u-picker :show="isPopup" ref="uPicker" :cancelText="$t('text.cancel')" confirmText="confirm" :columns="columns"
			:defaultIndex="defaultIndex" @cancel="handleCancel" @confirm="handleConfirm"
			@change="changeHandler"></u-picker>
	</view>
</template>

<script>
	import {
		showFailure,
		showMessage,
		showSuccess
	} from '../../lib/helper';
	import {
		policy,
		updateHouse,
		getHouseDetail,
		getArea,
		getAllArea,
	} from '../../lib/service';
	import {
		mapGetters
	} from 'vuex';
	export default {
		data() {
			return {
				id: '',
				mapname: this.$t('property.title.select.loaction'),
				longitude: "", //经度
				latitude: "", //纬度
				address: '',
				title: '',
				type: 1,
				floor: '',
				bedrooms: 5,
				bathrooms: 3,
				houseType: '2',
				area: 140,
				furnished: 0,
				rentPrice:"",
				familyPrice:"",
				weekDiscount:"",
				monthDiscount:"",
				radioList: [{
						name: this.$t('unfurnished'),
					},
					{
						name: this.$t('furnished'),
					},
				],
				unit: '1',
				period: '2',
				description: '',
				images: [],
				isPopup: false,
				country: [],
				city: [],
				region: [],
				columns: [],
				defaultIndex: [0, 0, 0],
				countryId: "", //国家id
				cityId: "", //城市id
				regionId: "", //地区id
				countryIndex: 0,
				cityIndex: 0,
				regionIndex: '',
				area_name: "",
				countryName: "",
				cityName: "",
				regionName: "",
				labels:"",
				cleanfee:"",
			};
		},

		onLoad(options) {
			let _this = this;
			var id = options.id;
			this.id = id;
			
			getHouseDetail(id).then((res) => {
				var house = res.data;
				this.countryId = house.countryId;
				this.cityId = house.cityId;
				this.regionId = house.regionId;
				this.longitude = house.longitude;
				this.latitude = house.latitude;
				this.mapname = house.mapname || this.$t('property.title.select.loaction');
				this.typeCheckbox = house.type.toString().split('');
				this.address = house.address;
				this.title = house.title;
				this.type = house.type;
				this.bedrooms = house.roomNum;
				this.bathrooms = house.toiletNum;
				this.houseType = house.propertyType + '';
				this.area = house.area;
				this.labels = house.labels;
				this.cleanfee = house.cleanfee;
				this.rentPrice = house.rentPrice;
				this.familyPrice = house.familyPrice;
				this.furnished = house.furnished;
				this.weekDiscount = house.weekDiscount;
				this.monthDiscount = house.monthDiscount;
				this.unit = house.payUnitType + '';
				this.period = house.payPeriodType + '';
				this.description = house.remark;
				this.images = house.photoUrls.split(',').map((item) => ({
					url: item
				}));
				_this.handleAreaAll()
			});
			// #ifdef APP-PLUS
			uni.$on("googleMsg", this.handleMessage1);
			// #endif
			// #ifdef H5
			window.addEventListener('message', this.handleMessage);
			// #endif

		},
		computed: {
			...mapGetters({
				cityItems: 'cityList',
				typeItems: 'saleType',
				houseItems: 'houseType',
				periodItems: 'pricePeriod',
				unitItems: 'priceUnit'
			}),
			weekPrice() {
				return this.familyPrice * (1 - this.weekDiscount / 100)
			},
			monthPrice() {
				return this.familyPrice * (1 - this.monthDiscount / 100)
			},
		},
		onShow() {
			let _this = this;
			uni.$on("isRefresh", function(data) {
				if (data.images) {
					let images = data.images;
					_this.images = _this.images.concat(images)
				}

			});
		},
		methods: {
			handleMessage(event) {
				if (!event.data.data) return;
				// 处理接收到的数据
				const {
					action,
					addresstxt,
					longitude,
					latitude
				} = event.data.data.arg;
				console.log('Received data from WebView-H5:', event.data);
				if(action === "chooseaddress"){
					this.mapname = addresstxt||this.$t('property.title.select.loaction');
					this.longitude = longitude; //经度
					this.latitude = latitude; //纬度
				}
			},
			handleMessage1(event) {
				if (!event.action) return;
				// 处理接收到的数据
				const {
					action,
					addresstxt,
					longitude,
					latitude
				} = event;
				console.log('Received data from WebView-APP:', event);
				if(action === "chooseaddress"){
					this.mapname = addresstxt||this.$t('property.title.select.loaction');
					this.longitude = longitude; //经度
					this.latitude = latitude; //纬度
				}
			},
			deletePic(event) {
				this.images.splice(event.index, 1);
			},
			// 所有城市数据
			handleAreaAll() {
				let _this = this;
				getAllArea().then(res => {
					if (res.statusCode == 0) {
						let data = res.data.country;
						if (data.length > 0) {
							_this.country = data;
							_this.countryId = _this.countryId ? _this.countryId : _this.country[_this.countryIndex]
								.id;
							_this.countryIndex = _this.country.findIndex(item => item.id === _this.countryId);
							_this.defaultIndex = [_this.countryIndex];
							let country = _this.country.find(item => item.id === _this.countryId);
							_this.countryName = country.name;
							_this.area_name = country.name;
							_this.handleArea(_this.country[_this.countryIndex].city)
						}
					}
				})
			},
			handleArea(city) {
				let _this = this;
				this.city = city || [];
				if (_this.city.length > 0) {
					this.cityId = this.cityId ? this.cityId : _this.city[_this.cityIndex].id;
					_this.cityIndex = _this.city.findIndex(item => item.id === _this.cityId);
					_this.defaultIndex = [_this.countryIndex, _this.cityIndex];
					let city = _this.city.find(item => item.id === _this.cityId);
					_this.cityName = city.name;
					_this.area_name = _this.countryName + '-' + city.name;
					_this.handleCity(_this.city[_this.cityIndex].region)
				}
			},
			handleCity(region) {
				let _this = this;
				_this.region = region || [];
				if (_this.region.length > 0) {
					_this.regionId = _this.regionId ? _this.regionId : _this.region[_this.regionIndex].id;
					_this.regionIndex = _this.region.findIndex(item => item.id === _this.regionId);
					_this.defaultIndex = [_this.countryIndex, _this.cityIndex, _this.regionIndex];
					let region = _this.region.find(item => item.id === _this.regionId);
					_this.regionName = region.name;
					_this.area_name = _this.countryName + '-' + _this.cityName + '-' + region.name;
				}
				_this.buildTree(_this.country, _this.city, _this.region);
			},
			buildTree(country, city, region) {
				let _this = this;
				let columns = [
					[],
					[],
					[]
				];
				let array = [];
				let array1 = [];
				let array2 = [];
				country.forEach(item => {
					array.push(_this.$i18n.locale == 'en' ? item.name : item.name2)
				})
				city.forEach(item => {
					array1.push(_this.$i18n.locale == 'en' ? item.name : item.name2)
				})
				region.forEach(item => {
					array2.push(_this.$i18n.locale == 'en' ? item.name : item.name2)
				})
				columns[0] = array;
				columns[1] = array1;
				columns[2] = array2;
				this.columns = columns;
			},
			handleShow() {
				this.isPopup = true;
			},
			handleCancel(e) {
				console.log(e)
				this.isPopup = false;
			},
			handleConfirm(e) {
				this.area_name = e.value.join('-');
				this.isPopup = false;
			},
			changeHandler(e) {
				let indexs = e.indexs;
				let value = e.value;
				if (e.columnIndex == 0 && indexs[0] >= 0) {
					this.countryId = this.country[indexs[0]].id;
					this.handleArea(this.countryId)
				} else if (e.columnIndex == 1 && indexs[1] >= 0) {
					this.countryId = this.country[indexs[0]].id;
					this.cityId = this.city[indexs[1]].id;
					this.handleCity(this.country[indexs[0]].id, this.city[indexs[1]].id)
				} else if (e.columnIndex == 2) {
					this.regionId = this.region[indexs[2]].id;
				}
			},
			handleRadio(index) {
				this.furnished = index;
			},
			reset() {
				this.cityId = '';
				this.countryId = '';
				this.regionId = "";
				this.area_name = '';
				this.address = '';
				this.title = '';
				this.type = 1;
				this.floor = '';
				this.bedrooms = 5;
				this.bathrooms = 3;
				this.houseType = '2';
				this.area = 140;
				this.labels = '';
				this.cleanfee = '';
				this.rentPrice = "";
				this.familyPrice = '';
				this.weekDiscount = "";
				this.monthDiscount = "";
				this.unit = '1';
				this.period = '2';
				this.description = '';
				this.images = [];
				this.longitude = ""; //经度
				this.latitude = ""; //纬度
				this.mapname = "";
			},

			handleSubmit() {
				let _this = this;
				if (this.title.length <= 0) {
					showMessage(this.$t('message.title.wrong'));
					return;
				}
				
				if (!_this.countryId && _this.cityId) {
					showMessage('Please select region');
					return;
				}
			    if (_this.furnished == 1) {
			    	if (!_this.familyPrice&&!_this.rentPrice) {
			    		showMessage('Please enter the long-term or short-term rental price');
			    		return;
			    	}
			    	if (_this.weekDiscount < 0 && _this.weekDiscount > 100) {
			    		showMessage('Weekly discount input range 1-100');
			    		return;
			    	}
			    	if (_this.monthDiscount < 0 && _this.monthDiscount > 100) {
			    		showMessage('Monthly discount input range 1-100');
			    		return;
			    	}
			    	if(_this.familyPrice){
			    		_this.type = 4
			    	}
			    	if(_this.rentPrice){
			    		_this.type = 1
			    	}
			    	if(_this.familyPrice&&_this.rentPrice){
			    		_this.type = 14
			    	}
			    }else{
			    	_this.type = 1;
			    	if (!_this.rentPrice) {
			    		showMessage(this.$t('message.title.rent'));
			    		return;
			    	}
			    	
			    }

				if (this.images.length <= 0) {
					showMessage(this.$t('message.images.wrong'));
					return;
				}
				var images = this.images.map((item) => item.url);
				var data = {
					title: this.title,
					countryId: this.countryId,
					cityId: this.cityId,
					regionId: this.regionId,
					longitude: this.longitude,
					latitude: this.latitude,
					mapname: this.mapname,
					address: this.address,
					area: this.area,
					type: this.type,
					roomNum: this.bedrooms,
					toiletNum: this.bathrooms,
					propertyType: this.houseType,
					furnished:this.furnished,
					labels:this.labels,
					cleanfee:this.cleanfee,
					rentPrice:this.rentPrice,
					familyPrice: this.familyPrice,
					payPeriodType: this.period,
					payUnitType: this.unit,
					photoUrls: images.join(','),
					logo: images[0],
					id: this.id,
					remark: this.description
				};
				if(this.furnished==1){
					data['weekDiscount'] = this.weekDiscount;
					data['monthDiscount'] = this.monthDiscount;
				}
				uni.showLoading();
				updateHouse(data).then((res) => {
					showSuccess();
					uni.hideLoading();
					uni.setStorageSync('location', null)
					this.reset();
					uni.navigateTo({
						url: '/pages/my-house/my-house'
					});
				}).catch((err) => {
					uni.hideLoading();
					showFailure();
				});
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.images.length;
				lists.map((item) => {
					this.images.push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i]);
					let item = this.images[fileListLen];
					this.images.splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(file) {
				let name = file.name ? file.name : file.url.split('/').pop();
				return new Promise((resolve, reject) => {
					policy('house', name).then((res) => {
						let a = uni.uploadFile({
							url: res.data.signedUrl, // 仅为示例，非真实的接口地址
							filePath: file.url,
							name: 'file',
							success: (res) => {
								try {
									var data = JSON.parse(res.data);
									resolve(data.data);
								} catch (e) {
									console.log(e);
								}
							}
						});
					});
				});
			},
			checkboxChange(e) {
				this.typeCheckbox = e;
				this.type = this.typeCheckbox.join('');
			},
			goWebView() {
				let language = uni.getStorageSync('language') || 'en';
				//该功能只能真机使用 仅限于 App  .nvue
				// #ifdef APP-PLUS
				uni.navigateTo({
					url: "/pages/submit/searchLocationApp?type=edit&language=" + language+"&id="+this.id
				})
				// #endif
			
				// #ifdef H5
				uni.navigateTo({
					url: "/pages/submit/searchLocation?type=edit&language=" + language+"&id="+this.id
				})
				// #endif
			},
			// 获取地图定位
			chooseLocation() {
				uni.navigateTo({
					url: "/pages/submit/searchLocation?type=edit&id=" + this.id
				})
			},
			handleCopy() {
				uni.navigateTo({
					url: "/pages/submit/copyUrl"
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.info_radio {
		margin-top: 40rpx;
	
		ul {
			display: flex;
			align-items: center;
	
			.active {
				p {
					color: #2879FF;
				}
			}
	
			li {
				margin-right: 70rpx;
	
				image {
					width: 36rpx;
					height: 36rpx;
				}
	
				p {
					padding-left: 16rpx;
					color: #999999;
				}
			}
		}
	}
	.submit-form {
		padding: 10px 30px 20px 30px;

		.form-item-title {
			margin-top: 20px;
			display: flex;
			align-items: center;
		}

		.copy {
			font-size: 24rpx;
			margin-top: 16rpx;
			display: inline-block;
			margin-left: 10rpx;
			color: #1890ff;
		}

		.form-input {}

		textarea {
			height: 140px;
			border: 1px solid $app-border-color;
			border-radius: 4px;
			width: 100%;
			padding: 10px;
			box-sizing: border-box;
		}
	}
</style>